package cn.starrysky.hrm.service.impl;

import cn.starrysky.hrm.client.CourseSearchClient;
import cn.starrysky.hrm.config.RabbitMQConfig;
import cn.starrysky.hrm.contants.CourseServiceContants;
import cn.starrysky.hrm.docment.CourseDoc;
import cn.starrysky.hrm.domain.Course;
import cn.starrysky.hrm.domain.CourseDetail;
import cn.starrysky.hrm.domain.CourseMarket;
import cn.starrysky.hrm.dto.CourseDto;
import cn.starrysky.hrm.enums.CourseGrade;
import cn.starrysky.hrm.mapper.CourseDetailMapper;
import cn.starrysky.hrm.mapper.CourseMapper;
import cn.starrysky.hrm.mapper.CourseMarketMapper;
import cn.starrysky.hrm.query.CourseDocQuery;
import cn.starrysky.hrm.service.ICourseService;
import cn.starrysky.hrm.usercontext.UserContextHolder;
import cn.starrysky.hrm.util.AjaxResult;
import cn.starrysky.hrm.util.PageList;
import cn.starrysky.hrm.utils.ValidUtils;
import cn.starrysky.hrm.vo.UserContext;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.plugin.liveconnect.SecurityContextHelper;

import java.io.Serializable;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author starrysky
 * @since 2021-03-06
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseSearchClient courseSearchClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional
    public void insertCourse(CourseDto dto) {
        Course course = dto.getCourse();
        //state 是否上线 默认下线0
        course.setStatus(CourseServiceContants.COURSE_STATUS_OFFLINE);
        //段位名字
        CourseGrade grade = CourseGrade.getGrade(course.getGradeId());
        ValidUtils.assertNotNull(grade, "没有这个等级");
        course.setGradeName(grade.getGradeName()); //设置等级名字
        //机构从登录信息中获取
        UserContext userContext = UserContextHolder.getUserContext();

        course.setUserId(userContext.getUserId());
        course.setUserName(userContext.getUsername());
        course.setTenantId(userContext.getTenantId());
        course.setTenantName(userContext.getTenantName());

        //保存course 返回主键
        courseMapper.insert(course);
        //绑定coursedetail的id
        CourseDetail courseDetail = dto.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);

        //绑定市场id
        CourseMarket courseMarket = dto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
    }


    //上线下线
    @Override
    public void onLineOrOffLine(Long courseId, boolean setStatus) {
        //获取course
        Course course = courseMapper.selectById(courseId);
        CourseDetail courseDetail = courseDetailMapper.selectById(courseId);
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseDoc courseDoc = new CourseDoc();
        //true 是上线 false 是下线
        if(setStatus){
            //先判断是否上线
            ValidUtils.assertCourseStatus(course.getStatus(),1 , "已经上线了！不能重复上线");
            //修改状态 上线1
            course.setStatus(1);
            course.setOnlineTime(new Date()); //上线时间
            course.setOfflineTime(null);
            //准备course coursedetail courseMarket
            BeanUtils.copyProperties(course, courseDoc);
            BeanUtils.copyProperties(courseDetail, courseDoc);
            BeanUtils.copyProperties(courseMarket, courseDoc);

            //将上线信息交给es 有可能保存不成功
            AjaxResult ajaxResult = courseSearchClient.addOrUpdate(courseDoc);
            ValidUtils.assertNotTrue(ajaxResult.isSuccess(),ajaxResult.getMessage());
            //最后更新course 状态
            courseMapper.updateById(course);

            //将上线信息发送到消息队列  短信 邮箱 站内
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,
                    "message.sms", course.getName());
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,
                    "message.email", course.getName());
            rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,
                    "message.system", course.getName());


        }else {
            //是否已经下线
            ValidUtils.assertCourseStatus(course.getStatus(),0 , "已经下线了！不能重复下线");
            //修改状态 下线
            course.setStatus(0);
            course.setOfflineTime(new Date());//下线时间
            //将下线从索引库中删除 有可能删除不成功
            AjaxResult ajaxResult = courseSearchClient.delete(courseId);
            ValidUtils.assertNotTrue(ajaxResult.isSuccess(),ajaxResult.getMessage());
            //更新数据库状态
            courseMapper.updateById(course);
        }
    }

    @Override
    public PageList<CourseDoc> queryCourses(CourseDocQuery docQuery) {
        //调用feign查询es索引库
        return courseSearchClient.queryCourses(docQuery);
    }

    //更新
    @Override
    @Transactional
    public void updateCourse(CourseDto dto) {
        System.out.println(dto.getCourse().getId());
//        Long id = dto.getCourse().getId();
//        Wrapper wrapper = new EntityWrapper<Object>().eq("id", id);
          //更新
//        courseMapper.update(dto.getCourse(),wrapper );
//        courseDetailMapper.update(dto.getCourseDetail(), wrapper);
//        courseMarketMapper.update(dto.getCourseMarket(), wrapper);
        Long id = dto.getCourse().getId();
        CourseDetail courseDetail = dto.getCourseDetail();
        courseDetail.setId(id);
        CourseMarket courseMarket = dto.getCourseMarket();
        courseMarket.setId(id);
        courseMapper.updateById(dto.getCourse());
        courseDetailMapper.updateById(courseDetail);
        courseMarketMapper.updateById(courseMarket);

    }


    //删除
    @Override
    @Transactional
    public boolean deleteById(Serializable id) {
        super.deleteById(id);
        courseDetailMapper.deleteById(id);
        courseMarketMapper.deleteById(id);
        return true;
    }
}
